package com.bestcem.xm.member.handler.imports.easyexcel;/*
package com.bestcem.xm.member.handler.imports.easyexcel;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bestcem.xm.member.entity.mysql.LabelValueId;
import com.bestcem.xm.member.entity.mongo.Member;
import com.bestcem.xm.member.grpc.service.param.imports.ImportMembersParam;
import com.bestcem.xm.member.service.ImportService;
import com.bestcem.xm.member.service.MemberService;
import com.bestcem.xm.member.service.dto.FieldDTO;
import com.bestcem.xm.member.service.dto.LabelDTO;
import com.bestcem.xm.member.service.dto.LabelValueDTO;
import com.bestcem.xm.member.util.CheckUtil;
import com.bestcem.xm.member.util.ImportRecordStatusEnum;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.stream.Collectors;

import static com.bestcem.xm.member.util.Constants.*;

*/
/**
 * 解析个人联系人数据
 *
 * @author yf.wang <yf.wang@idiaoyan.com>
 * @version V1.0
 * @date 2021/7/22
 *//*

@Slf4j
@Getter
@Setter
public class ReadIndividualMemberListener extends AnalysisEventListener<Map<Integer, String>> {

    */
/**
     * freeCount
     *//*

    private Long freeCount;

    private Map<String, String> storeNameIdMap;

    private List<String> headers;

    private ImportMembersParam param;

    private MemberService memberService;

    private ImportService importService;

    private Map<String, LabelDTO> labelMap;

    private Map<String, FieldDTO> fieldMap;

    private Integer per;

    private Integer count;

    private boolean isGetCount;

    private Boolean isStop;

    private JSONArray errorMsgJsons;

    @Override
    public void onException(Exception e, AnalysisContext analysisContext) throws Exception {
        if (log.isInfoEnabled()) {
            log.info("执行失败", e);
        }
    }

    */
/**
     * 获取表头数据
     *
     * @param map
     * @param analysisContext
     *//*

    @Override
    public void invokeHead(Map map, AnalysisContext analysisContext) {
        // 获取表头数据
        if (log.isInfoEnabled()) {
            log.info("开始获取表头数据");
        }
        headers = new ArrayList<>();
        map.forEach((k, v) -> {
            CellData v1 = (CellData) v;
            headers.add(v1.getStringValue());
        });
        if (CollUtil.isEmpty(headers)) {
            if (log.isInfoEnabled()) {
                log.info("没有表头数据");
            }
            isStop = true;
            return;
        }
        if (log.isInfoEnabled()) {
            log.info("开始校验表头数据");
        }
        // 校验表头
        Set<String> headerSet = new HashSet<>(headers.size());
        headerSet.addAll(headers);
        if (headers.size() != headerSet.size()) {
            // 列名不唯一
            isStop = true;
            // 更新错误信息
            importService.updateImportRecordErrorMessage("0", "列名不唯一", param.getRecordId(), ImportRecordStatusEnum.IMPORT_RECORD_STATUS_FAILED.getIndex());
            return;
        }
    }

    */
/**
     * 这个每一条数据解析都会来调用
     *
     * @param data
     * @param analysisContext
     *//*

    @Override
    public void invoke(Map<Integer, String> data, AnalysisContext analysisContext) {
        if (!isGetCount) {
            // 获取总行数
            Integer approximateTotalRowNumber =
                    analysisContext.readSheetHolder().getApproximateTotalRowNumber() - 1;
            count = approximateTotalRowNumber;
            if (approximateTotalRowNumber == 0) {
                // 没有数据
                isStop = true;
                return;
            }
            per = importService.getCalcUpdateProgressStep(count);
            // 初始化进度
            importService.setProgressBarStatus(0, param.getRecordId(), 0, count);
            isGetCount = true;
        }
        if (log.isInfoEnabled()) {
            log.info("解析到一条数据:{}", JSON.toJSONString(data));
        }
        // 获取当前解析的行数
        Integer rowIndex = analysisContext.readRowHolder().getRowIndex();
        // 每per条更新一次进度
        if (ObjectUtil.isNotEmpty(freeCount)) {
            // 非免费版
            handle(data, rowIndex);
        } else {
            if (freeCount == 0) {
                // 退出
                isStop = true;
                return;
            }
            handle(data, rowIndex);
            freeCount--;
        }
        if ((rowIndex - 1) % per == 0) {
            // 每per条更新一次进度
            importService.setProgressBarStatus(0, param.getRecordId(), (rowIndex - 1), count);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if (log.isInfoEnabled()) {
            log.info("所有数据解析完成");
        }
        // 处理错误信息

        //设置进度条结束
        importService.setProgressBarStatus(0, param.getRecordId(), count, count);
        int failedCount = errorMsgJsons.size();
        JSONObject dataJson = new JSONObject();
        dataJson.put("receiveCount", count);
        dataJson.put("successCount", count - failedCount);
        dataJson.put("failedCount", failedCount);
        dataJson.put("total_error_msg", errorMsgJsons);
        importService.updateImportRecordData(param.getRecordId(), dataJson, ImportRecordStatusEnum.IMPORT_RECORD_STATUS_SUCCESS.getIndex());
    }

    private ServiceResult<String> handle(Map<Integer, String> data, Integer rowIndex) {
        JSONObject memberJson = buildMemberJson(data);

        String errorMessage = checkErrorMsg(memberJson, rowIndex);
        if (StrUtil.isNotEmpty(errorMessage)) {
            JSONObject errorMsgJson = new JSONObject();
            errorMsgJson.put(String.valueOf(rowIndex), errorMessage);
            errorMsgJsons.add(errorMsgJson);
        }

        Member member = buildMember(memberJson, param);

        List<LabelValueId> memberLabels = new ArrayList<>();
        extendFieldLabel(memberJson, memberLabels);
        save(member, memberLabels);
        return ServiceResult.success();
    }


    */
/**
     * 构建数据
     *
     * @param data
     * @return
     *//*

    private JSONObject buildMemberJson(Map<Integer, String> data) {
        JSONObject memberJson = new JSONObject();
        JSONArray address = new JSONArray();
        Boolean isAddress = true;
        for (int i = 0; i < headers.size(); i++) {
            String headName = headers.get(i);
            if (ADDRESS_FIELDS.contains(headName)) {
                // 地址信息特殊处理
                String addressStr = data.getOrDefault(i, "");
                address.add(addressStr);
                if (StrUtil.isNotEmpty(addressStr)) {
                    isAddress = false;
                }
            } else {
                memberJson.put(INDIV_FIELD_NAME_AND_FIELD_MAP.get(headName), data.getOrDefault(i, ""));
            }
        }

        if (isAddress) {
            memberJson.put("address", new JSONArray());
        } else {
            memberJson.put("address", address.toString());
        }
        return memberJson;
    }


    */
/**
     * 校验数据
     *
     * @param memberJson
     * @param rowIndex
     *//*

    private String checkErrorMsg(JSONObject memberJson, Integer rowIndex) {
        StringBuilder errMessage = new StringBuilder();
        // 校验性别
        String gender = memberJson.getString("gender");
        if (!MEMBER_GENDER.contains(gender)) {
            errMessage.append("性别格式错误 ");
        }

        // 校验手机号
        String mobile = memberJson.getString("mobile");
        if (StrUtil.isNotEmpty(mobile)) {
            ServiceResult<String> result = CheckUtil.checkMobilePhoneFormat(mobile);
            if (!result.isSuccess()) {
                errMessage.append("手机号格式错误 ");
            }
        }

        // 校验邮箱
        String email = memberJson.getString("email");
        if (StrUtil.isNotEmpty(email)) {
            ServiceResult<String> result = CheckUtil.checkEmailFormat(email);
            if (!result.isSuccess()) {
                errMessage.append("邮箱格式错误 ");
            }
        }

        // 校验年龄
        String age = memberJson.getString("age");
        if (StrUtil.isNotEmpty(age)) {
            ServiceResult<String> result = CheckUtil.checkNumberFormat(age);
            if (!result.isSuccess()) {
                errMessage.append("年龄格式错误 ");
            }
        }

        // 校验生日
        String birthday = memberJson.getString("birthday");
        if (StrUtil.isNotEmpty(birthday)) {
            ServiceResult<String> result = CheckUtil.checkDateTimeFormat(birthday);
            if (!result.isSuccess()) {
                errMessage.append("生日格式错误 ");
            }
        }

        // 手机号码、邮箱、微信APPID，微信OPENID，支付宝ID至少出现一个
        String openId = memberJson.getString("openid");
        String aliPayUserId = memberJson.getString("alipay_user_id");
        String appId = memberJson.getString("appid");
        if (StrUtil.isEmpty(mobile) && StrUtil.isEmpty(email)
                && StrUtil.isEmpty(openId) && StrUtil.isEmpty(aliPayUserId)
                && StrUtil.isEmpty(appId)) {
            errMessage.append("手机号码、邮箱、微信APPID，微信OPENID，支付宝ID至少出现一个 ");
        }

        // 校验门店
//        String store = memberJson.getStr("store", "");
//        if (!storeNameIdMap.containsKey(store)) {
//            errMessage.append("所属组织不存在 ");
//        }

        log.info(" 第 {} 行 {}", rowIndex, errMessage.toString());
        return errMessage.toString();
    }

    */
/**
     * 构建联系人数据
     *
     * @param memberJson
     * @param param
     * @return
     *//*

    private Member buildMember(JSONObject memberJson, ImportMembersParam param) {
        Member member = memberService.queryMember(param, memberJson.getString(param.getPrimaryKey()));
        if (ObjectUtil.isNotEmpty(member)) {
            // 更新参数
            member.setSysId("member");
            member.setSource("excel");
            member.setName(dealUpdateField(memberJson.getString("name"), member.getName()));
            member.setEmail(dealUpdateField(memberJson.getString("email"), member.getEmail()));
            member.setMobile(dealUpdateField(memberJson.getString("mobile"), member.getMobile()));
            member.setGender(dealUpdateField(memberJson.getString("gender"), member.getGender()));
            member.setAppId(dealUpdateField(memberJson.getString("appid"), member.getAppId()));
            member.setOpenId(dealUpdateField(memberJson.getString("openid"), member.getOpenId()));
            member.setAlipayUserId(dealUpdateField(memberJson.getString("alipay_user_id"), member.getAlipayUserId()));
            // member.setStore(dealUpdateField(storeNameIdMap.get(memberJson.getStr("store")), member.getStore()));
            member.setAge(Integer.parseInt(dealUpdateField(memberJson.getString("age"), String.valueOf(member.getAge()))));

            // member.setBirthday(dealUpdateField(memberJson.getString("birthday"), member.getBirthday()));

            member.setMemberNo(dealUpdateField(memberJson.getString("memberNo"), member.getMemberNo()));

            member.setAddress(JSONArray.parseArray(dealUpdateField(memberJson.getString("address"), member.getAddress().toString())).toJavaList(String.class));
        } else {
            member = new Member();
            member.setOrgId(param.getOrgId());
            member.setSysId("member");
            member.setSource("excel");
            member.setName(memberJson.getString("name"));
            member.setEmail(memberJson.getString("email"));
            member.setMobile(memberJson.getString("mobile"));
            member.setGender(memberJson.getString("gender"));
            member.setAppId(memberJson.getString("appid"));
            member.setOpenId(memberJson.getString("openid"));
            member.setAlipayUserId(memberJson.getString("alipay_user_id"));
            // member.setStore(storeNameIdMap.get(memberJson.getStr("store")));
            member.setAge(memberJson.getIntValue("age"));
            member.setBirthday(memberJson.getDate("birthday"));

            member.setMemberNo(memberJson.getString("memberNo"));

            member.setAddress(memberJson.getJSONArray("address").toJavaList(String.class));
        }
        member.setMemberType(param.getAttribute());
        member.setNickname("");
        return member;
    }

    private String dealUpdateField(String inputValue, String exitValue) {
        if (StrUtil.isNotEmpty(inputValue)) {
            if (param.getExistedUpdate()) {
                return inputValue;
            }
        } else {
            if (param.getNullUpdate()) {
                return inputValue;
            }
        }
        return exitValue;
    }

    */
/**
     * 扩展字段 和 标签
     *
     * @param memberJson
     *//*

    private void extendFieldLabel(JSONObject memberJson, List<LabelValueId> memberLabels) {
        Collection<String> extendHeaders = CollUtil.subtract(headers, INDIVIDUAL_BASE_EXCEL_HEADERS);
        if (CollUtil.isNotEmpty(extendHeaders)) {
            extendHeaders.forEach(extendHeader -> {
                String field = memberJson.getString(extendHeader);
                // 如果存在该标签 且是可手动打标签的
                if (labelMap.containsKey(extendHeader) && labelMap.get(extendHeaders).getManual()) {
                    // 获取标签值id
                    LabelDTO labelDTO = labelMap.get(extendHeaders);
                    List<LabelValueDTO> values = labelDTO.getValues();
                    if (CollUtil.isNotEmpty(values)) {
                        List<LabelValueDTO> filterValues = values.stream().filter(value -> value.getValue().equals(field)).collect(Collectors.toList());
                        if (CollUtil.isNotEmpty(filterValues)) {
                            LabelValueDTO labelValueDTO = filterValues.get(0);
                            LabelValueId memberLabel = new LabelValueId();
                            memberLabel.setId(labelValueDTO.getId());
                            memberLabel.setLabelId(labelDTO.getId());
                            memberLabels.add(memberLabel);
                        }
                    }
                }

                // 扩展字段
                if (fieldMap.containsKey(extendHeader)) {
                    FieldDTO fieldDTO = fieldMap.get(extendHeader);
                    // 扩展字段id
                    String id = fieldDTO.getId();
                    // 扩展字段类型
                    Integer type = fieldDTO.getType();
                    // 校验扩展字段

                    // 保存扩展字段
                }

            });
        }
    }

    private void save(Member member, List<LabelValueId> memberLabels) {
        if (StrUtil.isNotEmpty(member.getId())) {
            Map<String, List<LabelValueId>> updateMemberLabelMap =
                    memberLabels.stream().collect(Collectors.groupingBy(LabelValueId::getId));
            Map<String, List<LabelValueId>> exitMemberLabelMap =
                    member.getLabels().stream().collect(Collectors.groupingBy(LabelValueId::getId));

            // 新的标签值
            Set<String> newLabelValueIds = updateMemberLabelMap.keySet();
            // 该联系人原有的标签值
            Set<String> oldLabelValueIds = exitMemberLabelMap.keySet();

            List<LabelValueId> lastLabel = new ArrayList<>();
            labelMap.forEach((name, obj) -> {
                // 获取所有的标签id
                List<String> allLabelValueId =
                        obj.getValues().stream().map(LabelValueDTO::getId).collect(Collectors.toList());
                // 新的标签值 在原有表里存在
                Collection<String> intersection = CollUtil.intersection(allLabelValueId, newLabelValueIds);
                if (CollUtil.isNotEmpty(intersection)) {
                    if (param.getExistedUpdate() && obj.getManual()) {
                        for (String newLabelId : intersection) {
                            lastLabel.add(updateMemberLabelMap.get(newLabelId).get(0));
                        }
                    } else if (!param.getExistedUpdate() && obj.getManual()) {
                        // 已存在的值不更新
                        Collection<String> intersectionOldTag = CollUtil.intersection(allLabelValueId, oldLabelValueIds);
                        if (CollUtil.isNotEmpty(intersectionOldTag)) {
                            for (String oldLabelId : intersectionOldTag) {
                                lastLabel.add(exitMemberLabelMap.get(oldLabelId).get(0));
                            }
                        }
                    }
                } else {
                    // 表里没有值
                    if (param.getNullUpdate() && obj.getManual()) {

                    } else {
                        Collection<String> intersectionOldTag = CollUtil.intersection(allLabelValueId, oldLabelValueIds);
                        if (CollUtil.isNotEmpty(intersectionOldTag)) {
                            for (String oldLabelId : intersectionOldTag) {
                                lastLabel.add(exitMemberLabelMap.get(oldLabelId).get(0));
                            }
                        }

                    }
                }
            });
            member.setLabels(lastLabel);
            memberService.updateImportMember(member);
        } else {
            // 创建
            member.setLabels(memberLabels);
            memberService.createImportMember(member);
        }
    }

    */
/**
     * 重写hasNext 为了实现有问题直接退出
     *
     * @param context
     * @return
     *//*

    @Override
    public boolean hasNext(AnalysisContext context) {
        return !isStop;
    }
}
*/
